// 数据示例（可替换为动态请求）
const mainImages = [
    {
        img: "https://cdn.jsdelivr.net/gh/Luoevanescence/static/nopeople-gym/static/stores/store_1.png",
        tagsUrl: "./static/img/mark1.png",
        title: "传说神剑",
        price: 999,
        tags: [
            { name: "传说", chance: 0.001 },
            { name: "史诗", chance: 0.015 },
            { name: "稀有", chance: 0.1258 },
            { name: "高级", chance: 0.8562 },
        ]
    },
    {
        img: "https://cdn.jsdelivr.net/gh/Luoevanescence/static/nopeople-gym/static/stores/store_2.png",
        title: "史诗战锤",
        tagsUrl: "./static/img/mark2.png",
        price: 799,
        tags: [
            { name: "传说", chance: 0.001 },
            { name: "史诗", chance: 0.015 },
            { name: "稀有", chance: 0.1258 },
            { name: "高级", chance: 0.8562 },
        ]
    },
    {
        img: "https://cdn.jsdelivr.net/gh/Luoevanescence/static/nopeople-gym/static/stores/store_3.png",
        title: "稀有护盾",
        tagsUrl: "./static/img/mark3.png",
        price: 599,
        tags: [
            { name: "传说", chance: 0.001 },
            { name: "史诗", chance: 0.015 },
            { name: "稀有", chance: 0.1258 },
            { name: "高级", chance: 0.8562 },
        ]
    },
    {
        img: "https://cdn.jsdelivr.net/gh/Luoevanescence/static/nopeople-gym/static/stores/store_4.png",
        title: "高级盔甲",
        tagsUrl: "./static/img/mark4.png",
        price: 499,
        tags: [
            { name: "传说", chance: 0.001 },
            { name: "史诗", chance: 0.015 },
            { name: "稀有", chance: 0.1258 },
            { name: "高级", chance: 0.8562 },
        ]
    },
];

const randomItems = [
    {
        image: "https://picsum.photos/id/1015/200/200",
        rarity: "传说",
        name: "烈焰圣剑",
        price: 999
    },

    {
        image: "https://picsum.photos/id/1044/200/200",
        rarity: "史诗",
        name: "星辰法杖",
        price: 780
    },

    {
        image: "https://picsum.photos/id/1074/200/200",
        rarity: "稀有",
        name: "魔力之戒",
        price: 450
    },

    {
        image: "https://picsum.photos/id/108/200/200",
        rarity: "高级",
        name: "高级生命药水",
        price: 120
    },
    {
        image: "https://picsum.photos/id/107/200/200",
        rarity: "高级",
        name: "火球术卷轴",
        price: 140
    },
    {
        image: "https://picsum.photos/id/109/200/200",
        rarity: "高级",
        name: "冒险者斗篷",
        price: 160
    }
];



const products = [
    { id: 1, title: "传说神剑", rarity: "传说", img: "https://picsum.photos/200/200?20", price: "99.99" },
    { id: 2, title: "史诗战锤", rarity: "史诗", img: "https://picsum.photos/200/200?21", price: "99.99" },
    { id: 3, title: "稀有护盾", rarity: "稀有", img: "https://picsum.photos/200/200?22", price: "99.99" },
    { id: 4, title: "高级盔甲", rarity: "高级", img: "https://picsum.photos/200/200?23", price: "99.99" },
    { id: 5, title: "传说魔杖", rarity: "传说", img: "https://picsum.photos/200/200?24", price: "99.99" },
    { id: 6, title: "史诗法袍", rarity: "史诗", img: "https://picsum.photos/200/200?25", price: "99.99" },
];
function goTo(path) {
  window.location.href = path;
}


function createCarousel(track, images, autoSpeed = 3000, renderSlide) {
    let currentIndex = 1;
    let isAuto = true;
    let autoTimer;
    let manualPauseTimeout = null;

    const firstClone = images[0];
    const lastClone = images[images.length - 1];

    function render() {
        track.innerHTML =
            `<div class="slide">${renderSlide(lastClone)}</div>` +
            images.map(item => `<div class="slide">${renderSlide(item)}</div>`).join('') +
            `<div class="slide">${renderSlide(firstClone)}</div>`;
        updatePosition(false);
    }

    function updatePosition(animate = true) {
        track.style.transition = animate ? "transform 0.3s ease" : "none";
        const slide = track.querySelector('.slide');
        if (!slide) return;
        const slideWidth = slide.offsetWidth;
        track.style.transform = `translateX(${-currentIndex * slideWidth}px)`;
    }

    function next() {
        if (currentIndex >= images.length) {
            currentIndex++;
            updatePosition(true);
            track.addEventListener("transitionend", () => {
                currentIndex = 1;
                updatePosition(false);
            }, { once: true });
        } else {
            currentIndex++;
            updatePosition(true);
        }
    }

    function prev() {
        if (currentIndex <= 1) {
            currentIndex--;
            updatePosition(true);
            track.addEventListener("transitionend", () => {
                currentIndex = images.length;
                updatePosition(false);
            }, { once: true });
        } else {
            currentIndex--;
            updatePosition(true);
        }
    }

    function startAuto() {
        autoTimer = setInterval(() => {
            if (isAuto) next();
        }, autoSpeed);
    }

    function stopAuto() {
        clearInterval(autoTimer);
    }

    function pauseAutoPlayTemporarily() {
        isAuto = false;
        stopAuto();
        if (manualPauseTimeout) clearTimeout(manualPauseTimeout);
        manualPauseTimeout = setTimeout(() => {
            isAuto = true;
            startAuto();
            manualPauseTimeout = null;
        }, 3000);
    }

    // Touch 支持
    let startX = 0;
    let deltaX = 0;
    track.parentElement.addEventListener("touchstart", (e) => {
        stopAuto();
        isAuto = false;
        if (manualPauseTimeout) {
            clearTimeout(manualPauseTimeout);
            manualPauseTimeout = null;
        }
        startX = e.touches[0].clientX;
    });
    track.parentElement.addEventListener("touchmove", (e) => {
        deltaX = e.touches[0].clientX - startX;
    });
    track.parentElement.addEventListener("touchend", () => {
        if (deltaX > 30) prev();
        else if (deltaX < -30) next();
        pauseAutoPlayTemporarily();
        deltaX = 0;
    });

    render();
    startAuto();

    return { next, prev, stopAuto, startAuto };
}


// 公共稀有度颜色映射
const rarityColorMap = {
    "稀有": "#e6c560",
    "史诗": "#6c54f7",
    "高级": "#1ea1fe",
    "传说": "#e63541"
};


// 渲染随机商品一件（简易轮播，左右切换同样逻辑）
function renderRandomItems(container, items) {
    const track = container.querySelector(".carousel-track");
    const containerWidth = container.offsetWidth;

    const imageWidth = 100;
    const gap = 10;
    const oriImagesWidth = (items.length * imageWidth + (items.length - 1) * gap);

    // ✅ 不足容器一半时，只渲染一轮
    const shouldScroll = oriImagesWidth >= containerWidth / 2;
    const allItems = shouldScroll ? [...items, ...items, ...items] : items;

    // 渲染内容（始终执行）
    track.innerHTML = allItems.map(item => `
        <div class="random-slide-item" onclick="goTo('http://127.0.0.1:5501/product-detail.html')">
            <img src="${item.image}" class="full-img" draggable="false" />
            <div class="tag-tips" style="background-color: ${rarityColorMap[item.rarity] || '#ccc'}">
            ${item.rarity}
            </div>
        </div>
        `).join('');


    // ✅ 延迟一帧，确保 DOM 渲染完成后再读宽度并开启动画
    requestAnimationFrame(() => {
        const trackWidth = track.scrollWidth;
        track.style.width = `${trackWidth}px`;

        if (!shouldScroll) return; // ✅ 不滚动就不进入动画 loop

        let offset = 0;
        const speed = 0.5;

        track.style.transition = "transform 0.3s linear";

        function loop() {
            offset -= speed;
            if (-offset >= trackWidth * 2 / 3) {
                track.style.transition = "none";
                offset += trackWidth / 3;
                track.style.transform = `translateX(${offset}px)`;
            } else {
                track.style.transform = `translateX(${offset}px)`;
            }
            requestAnimationFrame(loop);
        }

        requestAnimationFrame(loop);
    });
}








const rarityMap = {
    legendary: "传说",
    epic: "史诗",
    rare: "稀有",
    advanced: "高级",
    all: "all"
};
// 筛选商品列表
function renderProductList(container, products, filter) {
    container.innerHTML = "";


    const filterValue = rarityMap[filter];

    const filtered = filter === "all"
        ? products
        : products.filter(item => item.rarity === filterValue);
    filtered.forEach(product => {
        const item = document.createElement("div");
        item.className = "product-item";
        item.innerHTML = `
        <div class="product-item" onclick="goTo('http://127.0.0.1:5501/product-detail.html')">
            <div class="product-item-img">
            <img src="${product.img}" alt="${product.title}" />
            <div class="tag-tips" style="background-color: ${rarityColorMap[product.rarity] || '#ccc'}">
                ${product.rarity}
            </div>
            </div>
            <div class="title">${product.title}</div>
            <div class="price">        
            <div class="price-desc">参考价</div>
            <div class="price-unit">¥${product.price}</div>
            </div>
        </div>
        `;

        container.appendChild(item);
    });
}
//跳转商品详情
function bindClickNavigation(selector) {
    document.querySelectorAll(selector).forEach(el => {
        el.addEventListener("click", () => {
            window.location.href = "http://127.0.0.1:5501/product-detail.html";
        });
    });
}

bindClickNavigation(".product-item");
bindClickNavigation(".random-slide-item");
bindClickNavigation(".slide");

document.addEventListener("DOMContentLoaded", () => {
    // 主轮播图
    const mainTrack = document.querySelector(".main-carousel .carousel-track");
    createCarousel(mainTrack, mainImages, 2000, (item) =>  `<div onclick="goTo('http://127.0.0.1:5501/product-detail.html')">
  <img class="main-img" src="${item.img}" draggable="false" />
  <div class="info">
    <img class="tags-img" src="${item.tagsUrl}" />
    <div class="title">${item.title}</div>
    <div class="price">￥${item.price}</div>
  </div>
</div>`
);


    // 随机商品轮播
    const randomContainer = document.querySelector(".random-item-carousel");
    renderRandomItems(randomContainer, randomItems);

    // 筛选组合
    const productList = document.querySelector(".product-list");
    const filterBtns = document.querySelectorAll(".filter-btn");

    renderProductList(productList, products, "all");

    filterBtns.forEach(btn => {
        btn.addEventListener("click", () => {
            filterBtns.forEach(b => b.classList.remove("active"));
            btn.classList.add("active");
            const filter = btn.dataset.filter;
            renderProductList(productList, products, filter);
        });
    });

    // 回到顶部按钮逻辑
    const scrollTopBtn = document.getElementById("scrollTopBtn");
    const container = document.querySelector(".container");

    // 初始检查一次
    scrollTopBtn.style.display = container.scrollTop > 0 ? "block" : "none";

    // ✅ 用 container 替代 window 监听
    container.addEventListener("scroll", () => {
        scrollTopBtn.style.display = container.scrollTop > 0 ? "block" : "none";
    });

    scrollTopBtn.addEventListener("click", () => {
        container.scrollTo({ top: 0, behavior: "smooth" });
    });

    // “立即开盒”“开红包”按钮事件示例
    document.getElementById("openBoxBtn").addEventListener("click", () => {
        // alert("立即开盒 - 功能待实现");
    });
    document.getElementById("openRedPacketBtn").addEventListener("click", () => {
        // alert("开红包 - 功能待实现");
    });
});


const mask = document.getElementById("mask");
const modal = document.getElementById("productDetailModal");
const openBoxBtn = document.getElementById("openBoxBtn");
const closeModalBtn = document.getElementById("closeModalBtn");

function showModal() {
    mask.classList.remove("hidden");
    modal.classList.remove("hidden");
}

function hideModal() {
    mask.classList.add("hidden");
    modal.classList.add("hidden");
}

openBoxBtn.addEventListener("click", showModal);
closeModalBtn.addEventListener("click", hideModal);
mask.addEventListener("click", hideModal);


